package com.pzhyd.sc.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static SessionFactory sessionFactory = null;

	private static ThreadLocal threadLocal = new ThreadLocal();

	static {
		try {
			sessionFactory = new Configuration().configure()
					.buildSessionFactory();
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e.getMessage());
		}

	}

	private HibernateUtil() {
	}

	// 返回全新session
	public static Session getSession() {
		return sessionFactory.openSession();
	}

	// 返回一个和线程绑定的session
	public static Session getThreadLocalSession() {
		Session ses = (Session) threadLocal.get();
		if (ses == null) {
			ses = sessionFactory.openSession();
			threadLocal.set(ses);
		}
		return ses;
	}

	// 关闭和线程绑定的session
	public static void closeThreadLocalSession() {
		Session ses = (Session) threadLocal.get();
		if (ses != null && ses.isOpen()) {
			ses.close();
			threadLocal.set(null);
		}
	}
}